﻿using Microsoft.SystemCenter.Orchestrator.Integration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenerateReports
{
    [Activity("Folder Report")]
    public class FolderReport : ReportBase, IActivity
    {
        public void Design(IActivityDesigner designer)
        {
            string foldersUrl = config.ServiceUrl + "Folders";
            string data = Util.GetServiceData(foldersUrl);
            List<string> folderspath = Util.FindPropertyValueCollection(data, "Path");
            folderspath.Sort();

            designer.AddInput("Folder Path").WithListBrowser(folderspath);
            designer.AddInput("Report Path").WithFileBrowser();
        }

        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            string folderpath = request.Inputs["Folder Path"].AsString();
            string path = request.Inputs["Report Path"].AsString();
            string webresponse;
            string url;
            List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();

            // get folder Id
            url = config.ServiceUrl;
            url += "Folders?$filter=Path eq '" + folderpath + "'";
            webresponse = Util.GetServiceData(url);
            string folderid = Util.FindPropertyValue(webresponse, "Id");

            // get runbooks Id
            url = config.ServiceUrl;
            url += "Runbooks?$filter=FolderId eq Guid'" + folderid + "'";
            webresponse = Util.GetServiceData(url);
            List<string> runbooksid = Util.FindPropertyValueCollection(webresponse, "Id");

            // get all failed activities
            foreach (var i in runbooksid)
            {
                var list = GetFailedActivities(i);
                if (list.Count > 0)
                {
                    foreach(var j in list)
                    {
                        result.Add(j);
                    }
                }
            }

            Util.WriteToFile(result, path);
        }
    }
}
